package xyz.renyumeng.xkm.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import xyz.renyumeng.xkm.exception.XkmException;
import xyz.renyumeng.xkm.model.user.UserAddressInfo;
import xyz.renyumeng.xkm.model.user.UserInfo;
import xyz.renyumeng.xkm.result.Result;
import xyz.renyumeng.xkm.user.mapper.UserInfoMapper;
import xyz.renyumeng.xkm.user.service.UserAddressInfoService;
import xyz.renyumeng.xkm.user.service.UserInfoService;

import javax.annotation.Resource;

/**
 * @author renyumeng
 * @date Created in 16:27 2023/6/29
 */
@Service
@Transactional
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAddressInfoService userAddressInfoService;

    @Override
    public Result<UserInfo> getUserInfoByIdWithAddressInfo(Long id) {
        UserInfo userInfo = getUserInfoWithAddressInfo(id);
        return Result.ok(userInfo);
    }

    @Override
    public Result<Object> addUserById(UserInfo userInfo) {

        baseMapper.insert(userInfo);
        return Result.ok().message("添加成功!");
    }

    @Override
    public Result<Object> deleteUserById(Long id) {
        boolean status = this.removeById(id);
        if (!status) {
            throw new XkmException(201, "用户不存在，删除失败!");
        }
        return Result.ok().message("删除成功!");
    }

    @Override
    public UserInfo innerGetUserInfoByIdWithAddressInfo(Long id) {
        return getUserInfoWithAddressInfo(id);
    }

    private UserInfo getUserInfoWithAddressInfo(Long id) {
        UserInfo userInfo = baseMapper.selectById(id);
        Long userAddressId = userInfo.getUserAddressId();
        UserAddressInfo userAddressInfo = userAddressInfoService.getById(userAddressId);

        if (ObjectUtils.isEmpty(userInfo)) {
            throw new XkmException(201, "用户不存在!");
        }

        if (ObjectUtils.isEmpty(userAddressInfo)) {
            throw new XkmException(201, "地址信息不存在!");
        }
        Long userAddressInfoParentId = userAddressInfo.getParentId();
        UserAddressInfo userAddressParentInfo = userAddressInfoService.getById(userAddressInfoParentId);

        if (ObjectUtils.isEmpty(userAddressParentInfo)) {
            throw new XkmException(201, "地址信息不存在!");
        }
        String userAddress = userAddressInfo.getAddress();
        String userParentAddress = userAddressParentInfo.getAddress();
        String address = userParentAddress + ":" + userAddress;
        userInfo.getParam().put("addressInfo", address);
        return userInfo;
    }


}
